<template>
    <div class="marketing-applet-main">
        <div class="tabs">
            <div class="tabs-item">
                <div class="title">营销小程序</div>
                <div class="desc">应用于内容素材的分享查看、营销活动的参与等功能</div>
                <div class="button">
                    <el-button type="primary" @click="onAddApplet(1)">添加小程序</el-button>
                </div>
            </div>
            <div class="tabs-item">
                <div class="title">会员小程序</div>
                <div class="desc">应用于会员注册、会员信息查看、会员积分权益兑换等功能</div>
                <div class="member-button">
                    <div class="left">
                        <img
                            v-if="[8].includes(memberMiniAppInfo.status)"
                            src="@/assets/channelConfig/marketingApplet/icon_success.png"
                            alt="" />
                        <img
                            v-if="[1, 4, 5].includes(memberMiniAppInfo.status)"
                            src="@/assets/channelConfig/marketingApplet/icon_ing.png"
                            alt="" />
                        <img
                            v-if="[2, 3, 6, 7, 9].includes(memberMiniAppInfo.status)"
                            src="@/assets/channelConfig/marketingApplet/icon_error.png"
                            alt="" />
                        <div
                            :class="{
                                'member-status-green': [8].includes(memberMiniAppInfo.status),
                                'member-status-blue': [1, 4, 5].includes(memberMiniAppInfo.status),
                                'member-status-red': [2, 3, 6, 7, 9].includes(memberMiniAppInfo.status)
                            }">
                            {{ getStatusName(memberMiniAppInfo.status) }}
                        </div>
                    </div>
                    <el-button
                        v-if="!memberMiniAppInfo.is_member || [0, 2, 3, 9].includes(memberMiniAppInfo.status)"
                        type="primary"
                        @click="onAddApplet(2)">
                        添加小程序
                    </el-button>
                    <el-button
                        v-if="[4, 5, 6, 7].includes(memberMiniAppInfo.status)"
                        type="primary"
                        @click="onDetail(memberMiniAppInfo)">
                        查看
                    </el-button>
                </div>
            </div>
        </div>
        <el-scrollbar v-if="!isTableList" class="no-data-info">
            <div class="label-info">
                <div class="label">
                    <div class="label-title"><span>营销小程序介绍</span></div>
                    <div class="desc">
                        <div>
                            授权使用营销小程序可以将基础素材库中的内容（图片、音频、视频、文件）通过小程序雷达文件的形式发送给到客户，且获取到客户的手机号（小程序强制授权）。
                        </div>
                        <div>
                            营销小程序也同时支持智能营销模块的短链引流功能和抽奖裂变功能，授权营销小程序后，短链和抽奖裂变可以通过小程序的方式打开。
                        </div>
                    </div>
                    <div class="desc-img">
                        <div>
                            <img src="https://static.scrm.keyid.cn/assets/images/web-pc/marketing_applet__img1.jpg" />
                            <div class="desc-img-text">抽奖活动</div>
                        </div>
                        <div>
                            <img src="https://static.scrm.keyid.cn/assets/images/web-pc/marketing_applet__img2.jpg" />
                            <div class="desc-img-text">雷达素材</div>
                        </div>
                        <div>
                            <img
                                class="desc-img-right"
                                src="https://static.scrm.keyid.cn/assets/images/web-pc/marketing_applet__img3.jpg" />
                            <div class="desc-img-text desc-img-text-right">引流短链</div>
                        </div>
                    </div>
                </div>
                <div class="label">
                    <div class="label-title"><span>会员小程序介绍</span></div>
                    <div class="desc">
                        <div>
                            会员小程序可以帮助客户注册SCRM会员，如果SCRM系统绑定了抖店、淘宝店铺、小程序商城等，客户可以通过会员小程序绑定订单，进行积分兑换。客户也可以在会员小程序中的积分商城进行积分的消费。
                        </div>
                    </div>
                    <div class="desc-img desc-img-pt">
                        <div>
                            <img src="https://static.scrm.keyid.cn/assets/images/web-pc/member_applet_img1.jpg" />
                            <div class="desc-img-text">首页</div>
                        </div>
                        <div>
                            <img src="https://static.scrm.keyid.cn/assets/images/web-pc/member_applet_img2.jpg" />
                            <div class="desc-img-text">我的</div>
                        </div>
                    </div>
                </div>
            </div>
        </el-scrollbar>
        <div v-if="isTableList" class="marketing-applet-main_table">
            <ZwSearchForm :option="searchOption" @search="search" @reset="reset" @expand="expandHandle" />
            <ZwTable
                ref="tableRef"
                class="table-box"
                tab-h="initial"
                :option="tableOption"
                :row-key="getRowKey"
                :fetch-params="state.searchParams"
                :fetch-api="fetchApi()"
                @updateData="getTableData">
            </ZwTable>
        </div>
        <AppletDialog ref="appletDialogRef" />
        <FillInDialog ref="fillInDialogRef" />
        <el-dialog v-model="appDialog.visible" :title="appDialog.title" :width="appDialog.width">
            <div class="applet-content">
                <AddApplet :program-type="mini_program_type" />
            </div>
        </el-dialog>
    </div>
</template>
<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import AddApplet from './components/addApplet.vue';
import AppletDialog from './components/appletDialog.vue';
import FillInDialog from './components/fillinDialog.vue';
import Dialog from '@/components/Dialog.vue';
import { ElMessage, ElImage, ElIcon, ElButton, ElTooltip } from 'element-plus';
import { QuestionFilled } from '@element-plus/icons-vue';
import { ref, reactive, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { deepCopy } from '@/utils/helper';
import {
    getMarketingAppletList,
    getInstallLink,
    getMemberStatus,
    getMiniAppInfo
} from '@/api/channelconfig/marketingApplet';

const router = useRouter();
const route = useRoute();

const tableRef = ref<any>(null);
const appletDialogRef = ref<any>(null);
const fillInDialogRef = ref<any>(null);
const tableList = ref<any>([]);
const isTableSearch = ref<boolean>(false);
const isTableList = ref<boolean>(true);
const memberMiniAppInfo = ref<any>({});
const mini_program_type = ref<any>(1);

const appDialog = reactive<any>({
    visible: false,
    title: '添加小程序',
    width: '1000px',
    cancelText: '',
    submitText: ''
});

const miniAppStatusList = reactive([
    { value: 1, label: '注册审核中' },
    { value: 2, label: '注册审核不通过' },
    { value: 3, label: '授权失败' },
    { value: 4, label: '版本尚未发布' },
    { value: 5, label: '版本审核中' },
    { value: 6, label: '版本审核不通过' },
    { value: 7, label: '版本发布失败' },
    { value: 8, label: '运行中' },
    { value: 9, label: '取消授权' }
]);

const getStatusClass = (val?: any) => {
    const list = [
        { className: 'status_blue', code: '4' },
        { className: 'status_grey', code: '9' },
        { className: 'status_red', code: '2' },
        { className: 'status_red', code: '3' },
        { className: 'status_red', code: '6' },
        { className: 'status_red', code: '7' },
        { className: 'status_green', code: '8' },
        { className: 'status_blue', code: '1' },
        { className: 'status_blue', code: '5' }
    ];
    const info: any = list.find(el => el.code == val) || {};
    return info.className;
};

const getStatusName = (code?: any) => {
    const info: any = miniAppStatusList.find(el => el.value == code) || {};
    return info.label;
};

const searchOption = computed(() => {
    return [
        {
            label: '小程序名称',
            name: 'mini_app_name',
            type: 'input',
            clearable: true,
            placeholder: '请输入小程序名称'
        },
        {
            label: '状态',
            name: 'status',
            type: 'select',
            value: '',
            clearable: true,
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve(miniAppStatusList);
                });
            }
        },
        {
            label: '更新状态',
            name: 'verify_status',
            type: 'select',
            value: '',
            clearable: true,
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        // { value: 1, label: '未提审' },
                        { value: 2, label: '审核中' },
                        { value: 3, label: '审核失败' },
                        { value: 4, label: '取消审核' },
                        { value: 5, label: '发布成功' },
                        { value: 6, label: '发布失败' }
                    ]);
                });
            }
        },
        {
            label: '小程序类型',
            name: 'mini_program_type',
            type: 'select',
            value: '',
            clearable: true,
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { value: 1, label: '营销小程序' },
                        { value: 2, label: '会员小程序' }
                    ]);
                });
            }
        }
    ];
});

const tableOption = [
    {
        prop: '',
        label: '小程序',
        width: 360,
        renderHeader: () => {
            return (
                <div class="label_box">
                    <span>小程序</span>
                    <el-tooltip
                        placement="top"
                        effect="dark"
                        content="注册通过之前展示注册企业名称；注册通过并授权之后展示小程序头像、名称和主体">
                        <el-icon>
                            <QuestionFilled />
                        </el-icon>
                    </el-tooltip>
                </div>
            );
        },
        render({ row, column, index }: any) {
            return (
                <div class="applet-info">
                    <ElImage src={row.head_image} style="width: 36px; height: 36px;" />
                    <span> {row.nickname}</span>
                    <span>{row.principal_name && '(' + row.principal_name + ')'}</span>
                </div>
            );
        }
    },
    {
        prop: 'mini_program_type',
        label: '小程序类型',
        width: 180,
        render({ row, column, index }: any) {
            return (
                <div>{row.mini_program_type == 1 ? '营销小程序' : row.mini_program_type == 2 ? '会员小程序' : ''}</div>
            );
        }
    },
    {
        prop: '',
        label: '状态',
        width: 180,
        render({ row, column, index }: any) {
            return <div className={`${getStatusClass(row.status)} status`}>{row.status_name}</div>;
        }
    },
    {
        prop: 'version',
        label: '当前版本',
        width: 120
    },
    {
        prop: 'verify_version',
        label: '最新版本',
        width: 120
    },
    {
        prop: 'verify_status_name',
        label: '版本更新状态',
        width: 160
    },
    {
        prop: 'updated_at',
        label: '更新时间',
        width: 200
    },
    {
        prop: 'err_msg',
        label: '失败原因',
        showOverflowTooltip: true,
        minWidth: 160
    },
    {
        prop: 'have_open',
        label: '微信开放平台绑定状态',
        render({ row, column, index }: any) {
            return <div>{row.have_open == 1 ? '否' : row.have_open == 2 ? '是' : ''}</div>;
        },
        width: 180
    },
    {
        prop: 'is_principal',
        label: '绑定开放平台同主体',
        render({ row, column, index }: any) {
            return <div>{row.is_principal == 1 ? '否' : row.is_principal == 2 ? '是' : ''}</div>;
        },
        width: 160
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 180,
        isOperate: true,
        option: [
            {
                name: '重新授权',
                click: (row: any) => onAuth(row),
                isRender: ({ row }: any) => row.status == 3 || row.status == 9
            },
            { name: '重新注册', click: (row: any) => onRegister(row), isRender: ({ row }: any) => row.status == 2 },
            {
                name: '查看',
                click: (row: any) => onDetail(row),
                isRender: ({ row }: any) =>
                    row.status == 4 || row.status == 5 || row.status == 6 || row.status == 7 || row.status == 8
            },
            { name: '查看填写内容', click: (row: any) => onFillIn(row), isRender: ({ row }: any) => row.status == 1 }
        ]
    }
];

const defaultParams = {
    mini_app_name: '',
    status: '',
    verify_status: ''
};

const state = reactive({
    searchParams: deepCopy(defaultParams),
    searchHeight: '112px'
});

const getRowKey = (row: any) => {
    return row.id;
};

const search = (data: any) => {
    isTableSearch.value = true;
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy({ ...defaultParams, ...data });
};

const reset = () => {
    isTableSearch.value = true;
    tableRef.value.getTable().clearSelection();
    state.searchParams = deepCopy({ ...defaultParams });
};
/**
 * @description: 展开收起
 */
const expandHandle = (expand: boolean) => {
    state.searchHeight = expand ? '112px' : '64px';
};

const fetchApi = () => {
    return getMarketingAppletList;
};

const getTableData = (val?: any) => {
    tableList.value = val || [];
    if (!isTableSearch.value && !tableList.value.length) {
        isTableList.value = false;
    }
};

const onAddApplet = (type?: any) => {
    mini_program_type.value = type;
    appDialog.visible = true;
};

const onAuth = async (val: any) => {
    const params = {
        callback_front_url: 'https://' + window.location.host + '/redirect-info-guide?type=mp',
        auth_type: 2,
        mini_program_type: val.mini_program_type
    };
    const res = await getInstallLink(params);
    if (res.url) {
        window.open(res.url, '_blank');
    }
};

const onRegister = (val: any) => {
    if (val.reg_type == 1) {
        router.push({
            path: '/channelconfig/qywechat/marketingApplet/registerFillin',
            query: {
                id: val.id,
                type: val.mini_program_type
            }
        });
    } else {
        onAuth(val);
    }
};

const onFillIn = (val: any) => {
    fillInDialogRef.value.appDialog.id = val.id;
    fillInDialogRef.value.appDialog.visible = true;
};

const onDetail = (val: any) => {
    router.push({
        path: '/channelconfig/qywechat/marketingApplet/detail',
        query: {
            id: val.id
        }
    });
};

const initMemberApplet = async () => {
    const res = await getMemberStatus();
    memberMiniAppInfo.value = res || {};
};

initMemberApplet();
</script>
<style lang="scss" scoped>
.marketing-applet-main {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;

    .no-data-info {
        flex: 1;

        .content {
            padding-top: 72px;
            text-align: center;

            .bg-img {
                width: 280px;
                height: 288px;
            }

            .desc-text {
                font-size: 16px;
                color: #585858;
                line-height: 22px;
            }
        }

        .app-applet {
            margin: 76px auto;
            width: 70%;
        }

        .label-info {
            display: flex;
        }

        .label {
            margin: 6px 90px 30px 0;

            .label-title {
                font-size: 16px;
                font-weight: 600;
                color: #33302d;
                line-height: 18px;
                position: relative;

                span {
                    padding-left: 12px;
                }

                &::before {
                    display: inline-block;
                    position: absolute;
                    top: 1px;
                    width: 4px;
                    height: 16px;
                    content: '';
                    background: #ff6b00;
                }
            }

            .desc {
                padding-top: 16px;
                font-size: 14px;
                color: #585858;
                line-height: 20px;
                min-height: 80px;
            }

            .desc-img {
                padding-top: 31px;
                display: flex;

                img {
                    margin-right: 30px;
                    width: 208px;
                }

                .desc-img-right {
                    margin-right: 0;
                }

                .desc-img-text {
                    margin-right: 30px;
                    padding-top: 14px;
                    text-align: center;
                    font-size: 14px;
                    color: #585858;
                    line-height: 20px;
                }

                .desc-img-text-right {
                    margin-right: 0;
                }
            }
        }
    }

    .marketing-applet-main_table {
        flex: 1;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        .zw-table {
            display: flex;
            flex-direction: column;
            flex: 1;
            overflow: hidden;

            :deep(.el-table) {
                flex: 1;

                .el-table__empty-block {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }
            }
        }
    }

    :deep(.applet-info) {
        display: flex;
        align-items: center;

        span {
            margin-left: 10px;
        }
    }

    :deep(.status) {
        display: flex;
        align-items: center;

        &::before {
            display: inline-block;
            width: 8px;
            height: 8px;
            margin-right: 6px;
            content: '';
            border-radius: 4px;
            background: #ccc;
        }
    }

    :deep(.status_grey::before) {
        background: #d8d8d8;
    }

    :deep(.status_orange::before) {
        background: #ff6b00;
    }

    :deep(.status_blue::before) {
        background: #2fb6e4;
    }

    :deep(.status_yellow::before) {
        background: #ffd500;
    }

    :deep(.status_red::before) {
        background: #f14144;
    }

    :deep(.status_green::before) {
        background: #60b900;
    }

    :deep(.label_box) {
        display: flex;
        align-items: center;

        span {
            padding-right: 12px;
        }
    }

    .applet-content {
        margin: 40px 60px;
    }

    .tabs {
        display: flex;
        align-items: center;

        .tabs-item {
            margin: 0 24px 24px 0;
            padding: 24px;
            width: 294px;
            height: 134px;
            background: #fff;
            border-radius: 4px;
            border: 1px solid #eaeaea;

            .title {
                font-size: 16px;
                color: #33302d;
                line-height: 22px;
            }

            .desc {
                padding: 16px 0;
                font-size: 14px;
                color: #666;
                line-height: 20px;
            }

            .button {
                text-align: right;
            }

            .member-button {
                display: flex;
                justify-content: space-between;
                align-items: center;

                .left {
                    display: flex;
                    align-items: center;
                    font-size: 14px;
                    color: #33302d;

                    img {
                        margin-right: 4px;
                        width: 16px;
                        height: 16px;
                    }

                    .member-status-red {
                        color: #fe292b;
                    }

                    .member-status-blue {
                        color: #2fb6e4;
                    }

                    .member-status-green {
                        color: #60b900;
                    }
                }
            }
        }

        .tabs-item:hover {
            box-shadow: 0 2px 24px 0 rgb(234 234 234 / 100%);
        }
    }
}
</style>
